from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.contrib.auth.hashers import make_password,check_password
from tools.generate import token_duc,pars_token
from django.db import transaction
import random
import string

# Create your views here.
class UserViews(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        code=request.data.get('code')
        user_count=Users.objects.all().count()
        #判断一下当前用户是否是第一个用户，如果是第一个用户 否则邀请码
        if user_count==0:
            if code!='#':
                return Response({
                    'code':400,
                    'msg':'验证码错误'
                })
        else:
        # 不是第一个用户，验证码是否存在
             user_info=Users.objects.filter(rec_code=code).first()
             if  not user_info:
                 return Response({
                     'code':400,
                     'msg':'验证码错误'
                 })
             pwd=make_password(password)
#         生成唯一码，并保证唯一
             while True:
                    shar_code=''.join(random.sample(string.ascii_letters+string.digits,8))
        #             推荐码=推荐码
                    shar_user=Users.objects.filter(rec_code=shar_code).first()
                    if not shar_user:
                        break

                    Users.objects.create(
                        username=username,
                        password=pwd,
                        code=code,
                        rec_code=shar_code,
                        total=0
                    )
             return Response({
                 'code':200,
                 'msg':'注册成功',
                 'share_code':shar_code,
             })
    def put(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        user_info=Users.objects.filter(username=username).first()
        if not user_info:
            return Response({
                'code':400,
                'msg':'用户不存在'
            })
        if not check_password(password,user_info.password):
            return Response({'code':400,'msg':'密码错误'})
        token=token_duc('user')
        return Response({
            'code':200,
            'mag':'登录成功',
            'token':token
        })

# 充值
class Recharage(APIView):
    def put(self,request):
        username=request.data.get('username')
        total=request.data.get('total')
        token=request.data.get('token')
        total=float(total)
        if not token:
            return Response({'code':400,'msg':'用户未登录'})
        rest=pars_token(token)
        r=rest.get('id')
        if r !=1:
            return Response({'code':400,'msg':'无权操作'})
        user_info=Users.objects.filter(username=username).first()
        if not user_info:
            return Response({'code':400,'msg':'用户不存在'})
        user_info.total=float(user_info.total)+total
        user_info.save()
        return Response({'code':200,'msg':'充值成功'})

class GoodsViews(APIView):
    def post(self,request):
        goods_id=request.data.get('goods_id')
        token=request.data.get('token')
        count=request.data.get('count')
        count=int(count)
        if not token:
            return Response({'code':400,'msg':'用户未登录'})
        rest=pars_token(token)
        r=rest.get('id')
        goods_info=Goods.objects.filter(id=goods_id).first()
        user_info=Users.objects.filter(id=r)
        if user_info.total<goods_info.price*count:
            return Response({'code':400,'msg':'余额不足'})
#         开启事物
        with transaction.atomic():
            # 设置一个事物的回滚点
            point=transaction.savepoint()
            try:
                buy_count=Orders.objects.filter(user_id=r).filter(goods_id=goods_id).all().count()
                if buy_count%4==3:
                    price=goods_info.price/2
                else:
                    price=goods_info.price
                Orders.objects.create(
                    goods=goods_info,
                    user=user_info,
                    count=count,
                    total_price=price*count,
                    status=1,
                )
                user_info.total=float(user_info.total)-float(price*count)
                user_info.save()
                # 给推荐人返还10%的金额
                m=float(price)*count*0.1
                #找到推荐人
                share_user=Users.objects.filter(rec_code=user_info.code).first()
                if not share_user:
                    share_user.total=float(share_user.total)+float(m)
                    share_user.save()
            except Exception as e:
                print(e)
                transaction.savepoint_rollback(point)
                return Response({'code':400,'msg':'购买失败'})
            transaction.savepoint_commit(point)
            return Response({'code':200,'msg':'购买成功'})







